<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="报损申请单" color="#000000" backgroundColor="#FFFFFF" :storeName="sUserStoreName" :storeId="sUserStore"
                :option="nbOption" @menuFunc="onClickMenuFunc" @onClickStore="clickStore"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="true">
        <template v-slot:searchFields>
          <view class="search-fields">
            <eui-card-input v-model="formData.c_id" title="单据号"
                            placeholder="请输入单据号" type="text" :displayable="displayable" />
            <eui-card-input v-model="formData.c_mk_dt_s" title="开始日期"
                            placeholder="请选择录入开始日期" type="date" :displayable="displayable" />
            <eui-card-input v-model="formData.c_mk_dt_e" title="结束日期"
                            placeholder="请选择录入结束日期" type="date" :displayable="displayable" />
            <view class="bottom flex-1 flex">
              <eui-button type="max2" title="重置" singleTag="reset" @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm"></eui-button>
            </view>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" @itemClick="onClickGoToDetail" :origList="dataList" isBottom="true"  titleField="c_id" type="list">
        <template v-slot:list="scope">
          <eui-text title="仓库" :value="scope.c_wno" :name="getRelatedName('rdsWnos', scope.c_wno)" type="titlename2" />
          <eui-text title="部门" :value="scope.c_adno" :name="getRelatedName('rdsDeparts', scope.c_adno)" type="titlename2" />
          <eui-text title="损溢性质" :value="getDictName('损溢性质', scope.c_pal_kind)" type="name2" />
          <eui-text title="损溢方向" :value="getDictName('损溢方向', scope.c_pal_flag)" type="name2" />
          <eui-text title="录入" :value="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)" type="titlename2" />
          <eui-text :value="scope.c_mk_dt" type="rdstime2" />
          <eui-text title="审核" :value="scope.c_au_userno" :name="getRelatedName('rdsUsers', scope.c_au_userno)" type="titlename2" v-if="!['0', '2', '9'].includes(scope.c_status)" />
          <eui-text :value="scope.c_au_dt" type="rdstime2" v-if="!['0', '2', '9'].includes(scope.c_status)" />
        </template>
        <template v-slot:bottom="scope">
          <view v-if="scope.c_status !== '0'" class="gap-left">
            <eui-button :modelValue="scope" type="min" single-tag="detail" title="详情" @buttonClick="buttonClick" />
          </view>
          <view v-if="scope.c_status === '0'" class="gap-left">
            <eui-button :modelValue="scope" :type="scope.c_status == '0' && scope.c_approve_status == '1' ? 'min2' : 'min'" single-tag="edit" title="编辑" @buttonClick="buttonClick" />
          </view>
          <view v-show="scope.c_status == '0' && scope.c_approve_status == '1'" class="gap-left">
            <eui-button :modelValue="scope" type="min" single-tag="approve" :title="sysConfig.isApprove ? '审批' : '审核'" @buttonClick="buttonClick" />
          </view>
        </template>
      </eui-virtual-list>
    </view>
  </view>
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import { validateStores } from '@/hooks/useValidateMethod';
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import { getRelatedName, getDictName } from '../components/RelatedName.js';
import service from "@/common/service";
import dateRangUtil from '../../../common/dateRangUtil';
import {onLoad} from "@dcloudio/uni-app";
import { init, getRdsSysConfig } from '@/hooks/init';
import Enjoy from "@/common/enjoy";
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const searchText = ref('');
const CurrentPage = ref(1);  //第几页
const PageSize = ref(10);  //每页10条
const RowsCount = ref(0);  //总条数
const PageCount = ref(1);  //总页数
const displayable = ref(false);  //true允许页面编辑
const dataList = ref([]);
const sysConfig = ref({
  isApprove: '',//商品验收单是否审批
});
const mainData = ref({});
const c_status = ref('0');
const nbOption = ref({
  items: [
    {title: '新增单据', onClick: 'onClickNewCount', icon: 'plusempty'},
  ]
})
const formData = ref({
  c_mk_dt_s: (dateRangUtil.getLast1Month())[0],
  c_mk_dt_e: (dateRangUtil.getLast1Month())[2],
  c_id: '',
})
const listHeight = ref(300);  //列表高度
const RdsSearchBar = ref(null);
const EuiNavBar = ref(null);

onLoad(async () => {
  await init();
  await getSysConfig();
  const { loginInfo } = mainStore;
  if (!loginInfo.sUserStore) {
    EuiNavBar.value.onClickStore();
    return;
  }
  await setDefault();
  await getData();
})

const getSysConfig = async () => {
  sysConfig.value.isApprove = await getRdsSysConfig("单据是否审批", "损溢申请单") === '是';
}

const setDefault = async () => {
  const { loginInfo } = mainStore;
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
}

// 选择框点击事件
const clickStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = "机构选择";
  parms.SelectedItems = sUserStore.value;
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (event) => {
  if (event.SelectionType == '机构选择') {
    // 更新机构信息
    sUserStoreName.value = event.BackParms.Value;
    sUserStore.value = event.BackParms.Key;
  }
  // 按新条件获取数据
  await getData();
}

const getData = async (e) => {
  if (!e) {
    CurrentPage.value = 1;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    UserNo: sUser.value,
    WhereList: [
      { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
      { c_col: "c_pal_flag", c_oper: "等于", c_value: '1', c_logic: "而且" },
      { c_col: "c_mk_dt", c_oper: "大于等于", c_value: formData.value.c_mk_dt_s, c_logic: "而且", c_col_dtype: "System.DateTime" },
      { c_col: "c_mk_dt", c_oper: "小于等于", c_value: formData.value.c_mk_dt_e, c_logic: "而且", c_col_dtype: "System.DateTime" },
      formData.value.c_id ? { c_col: "c_id", c_oper: "等于", c_value: formData.value.c_id, c_logic: "而且" } : {},
    ]
  }
  if (searchText.value) {
    req.WhereList.push({
      c_col: "c_gcode",
      c_oper: "等于",
      c_value: searchText.value,
      c_logic: "而且",
    });
  }
  const result = await rdsRequest(rdsUrl.scApi, '损溢申请单', 'EnjoyQueryList', req, "7F1");
  CurrentPage.value = result.CurrentPage; //第几页
  PageSize.value = result.PageSize; //每页10条
  RowsCount.value = result.RowsCount; //总条数
  PageCount.value = result.PageCount; //总页数
  if (result.CurrentPage == 1) {
    dataList.value = result.ReturnObject;
  } else {
    dataList.value = dataList.value.concat(result.ReturnObject);
  }
  service.enjoyHideLoading();
}

const listPullDown = () => {
  CurrentPage.value = 1;
  getData();
}

const listPullUp = (e) => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    getData(true);
  }
}

const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  searchText.value = e.value;
  await getData();
}

// 上拉加载更多
const templateLower = () => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    getData(true);
  }
}

const onClickGoToDetail = (e) => {
  let { index, item } = e;
  uni.navigateTo({
    url: './edit?c_id=' + item.c_id + '&storeId=' + sUserStore.value
  });
}

// 新增单据
const onClickMenuFunc = (e) => {
  switch (e) {
    case 'onClickNewCount':
      setTimeout(() => {
        EuiNavBar.value.closeDrawer();
      },1200);
      uni.navigateTo({
        url: './edit?storeId=' + sUserStore.value
      });
      break;
  }
}

// 审批
const approve =(req) => {
  const { loginInfo } = mainStore;
  if (mainData.value.c_approve_status == "1") {
    uni.showModal({
      title: ' 提示',
      content: '请确认，单据[' + req.BillId + ']发起审批?',
      showCancel: true,
      success: async (res) => {
        if (res.confirm) {
          await sendApprove();
        }
      }
    });
  } else {
    const item = {
      c_approve_status: mainData.value.c_approve_status,
      Id: mainData.value.c_id,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
      AppParam: '商品补货申请单',
    }
    const request = {
      Id: req.BillId,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
    }
    // apps.ApprovePath(request, item, res => { }, res => { });
  }
}

const auditBill = (req) => {
  if (mainData.value.c_status == '0') {
    uni.showModal({
      title: ' 提示',
      content: '请确认，审核单据[' + req.BillId + ']?',
      showCancel: true,
      success: async (res) => {
        if (res.confirm) {
          service.enjoyShowLoading('正在审核...');
          const result = await rdsRequestAsync(rdsUrl.scApi, '损溢申请单', 'EnjoyBillAudit', req, '701');
          if (result.HasException) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: result.Exception.Message
            });
          } else {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: '审核成功！'
            });
          }
          await getData();
        }
      }
    });
  }
}

const sendApprove = async() => {
  const { loginInfo } = mainStore;
  const ApproveBills = {
    AppPage: "/modules/ic/rec/rec/list",
    AppParam: "损溢申请单",
    AppUsers: [],
    BillId: mainData.value.c_id,
    BillKey: mainData.value.c_id,
    BillRealType: "损溢申请单",
    BillType: "损溢申请单",
    CFGName: "损溢申请单",
    FlowGuid: "e41e4780-fb44-407f-9757-95074e1ee46b",
    FlowName: "损溢申请单",
    HtmlContent: "",
    HtmlMobileContent: "",
    IsMainFlow: true,
    IsCanTempApp: false,
    IsSelected: true,
    IsTempApp: false,
    MdCode: "rds_ic_po_pal",
    NoticType: "",
    ProjectName: "RDS", // OA\RMIS\RMISNew,
    StoreId: mainData.value.c_store_id,
    AppReqUserNo: loginInfo.sUser,
    UserNo: loginInfo.sUser,
    TempTitle: `单据:${mainData.value.c_id}`,
    // ApproveServiceUrl: Url.EnjoyRMIS,
  }
  const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'SendApprove', ApproveBills, '701');
  if (approveResult.Result) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '发送审批成功！'
    });
    await getData();
  }
}

// 点击扫描图标跳转打开摄像头
const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        getData();
      }
    },
  });
}

const buttonClick = (e) => {
  const { loginInfo } = mainStore;
  let { singleTag, modelValue, type } = e;
  switch (singleTag) {
    case 'approve':
      const req = {
        BillId:  modelValue.c_id,
        UserNo: loginInfo.sUser,
        StoreId: modelValue.c_store_id,
      }
      mainData.value = modelValue;
      if (sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审批
        approve(req);
      }
      if (!sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审核
        auditBill(req);
      }
      break;
    case 'detail':
      uni.navigateTo({
        url: './edit?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
      });
      break;
    case 'edit':
      if (modelValue.c_status == '0') {
        uni.navigateTo({
          url: './edit?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
        });
      }
      break;
  }
}

const confirm = (t) => {
  let { singleTag } = t;
  switch (singleTag) {
    case 'reset':
      formData.value.c_mk_dt_s = (dateRangUtil.getLast1Month())[0];
      formData.value.c_mk_dt_e = (dateRangUtil.getLast1Month())[2];
      formData.value.c_id = '';
      break;
    case 'fix':
      getData();
      // 关闭弹出层
      RdsSearchBar.value.closeDrawer();
      break;
  }
}




</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;
}
.main-view {
  flex: 1;
  flex-direction: column;
}
.search-fields {
  width: 100%;
  background: #FFFFFF;
  position: relative;

  .bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
  }
}
.gap-left {
  margin-left: 20rpx;
}
</style>
